<template>
  <uv-upload
      :fileList="imageList"
      :name="name"
      :uploadIcon="uploadIcon"
      :uploadText="uploadText"
      :width="width"
      :height="height"
      :custom-style="customStyle"
      multiple
      :disabled="disabled"
      :maxCount="maxCount"
      :deletable="deletable"
      :useBeforeRead="true"
      @beforeRead="beforeRead"
      @afterRead="afterRead"
      @delete="fileDelete"
  ></uv-upload>
</template>
<script setup>
import { generateNonceStr } from '@/utils/crypto';
import {ref, reactive, getCurrentInstance, defineEmits, watchEffect} from 'vue'
const {proxy} = getCurrentInstance()
import api from '@/api/upload/upload'

const props = defineProps({
  parentImageList:{
    type:Array,
    default: []
  },
  tableId: {    // 表id
    type: String,
    default: ''
  },
  tableName: {      // 表名称
    type: String,
    default: ''
  },
  type: {                 // 文件类型
    type: String,
    default: ''
  },
  maxCount:{               //最大选择图片的数量
    type:Number,
    default:5
  },
  //上传区域的图标，只能内置图标
  uploadIcon:{
    type:String,
    default:'plus'
  },
  //是否启用(显示/隐藏)组件
  disabled:{
    type:Boolean,
    default:false
  },
  //标识符，可以在回调函数的第二项参数中获取
  name:{
    type:String,
    default:'upload'
  },
  //是否显示删除按钮
  deletable:{
    type:Boolean,
    default:true
  },
  //上传区域的提示文字
  uploadText:{
    type:String,
  },
  //内部预览图片区域和选择图片按钮的区域宽度，单位rpx，不能是百分比，或者auto
  width:{
    type:Number||String||Object
  },
  //内部预览图片区域和选择图片按钮的区域高度，单位rpx，不能是百分比，或者auto
  height:{
    type:Number||String
  },
  //自定义外部样
  customStyle:{
    type:Object,
  },
  // 是否加水印
  watermarkFlag:{
    type:Boolean,
    default: false
  },
  // 地点
  place:{
    type:String,
    default:''
  },
})
let imageList = ref([]);           // 图片列表
let addList = [];           // 图片新增列表
let delList =  [];           // 删除文件
let uploadIf = ref(true)
const emits = defineEmits(['imageListArray','initImage','delImageListArray']);
imageList.value = props.parentImageList;
const beforeRead = async (e)=>{
  const size = (e.file.size) / 1024 / 1024
  let index;
  let type;
  // #ifdef APP-PLUS || H5
  index = e.file.name.indexOf('.')
  type = e.file.name.substring(index + 1)
  // #endif
  // #ifdef MP-WEIXIN
  index = e.file.url.indexOf('.')
  type = e.file.url.substring(index + 1)
  // #endif
  if (type !== 'png' && type !== 'jpg' && type !== 'jpeg') {
    uni.showToast({
      icon:'none',
      title:'文件格式不正确, 请上传png/jpg/jpeg图片格式文件'
    })
    uploadIf.value = false
    return false
  }else {
    if (size > 10) {
      uni.showToast({
        icon:'none',
        title:'文件大小超过限制，最多不能超过10M'
      })
      uploadIf.value = false
    }else {
      uploadIf.value = true
    }
  }
}
// 初始化数据
let init = async (e) => {
  if(props.parentImageList.length === 0){
    imageList.value = [];
  }
  delList = [];
  addList = [];
  if(props.tableId) {
    let query = {};
    query.tableId = props.tableId;
    query.tableName = props.tableName;
    if(props.type){
      query.type = [props.type];
    }
    let res = await proxy.http.asyncPost(api.findFileList, query);
    if (res.code === 0) {
      imageList.value = res.data;
      emits('initImage',imageList.value,props.type);
    } else {
      uni.showToast({title: res.msg, icon: 'none'});
    }
  }
}



// 删除图片
let fileDelete = (e, key) => {
  if(e.file.id) {                       // 删除已上传文件回信文件
    let delIndex = null;
    imageList.value.filter((item, index) => {
      if (item.id === e.file.id) {
        delIndex = index;
      }
      return item;
    });
    imageList.value.splice(delIndex, 1);
    delList.push(e.file.id)
    emits('delImageListArray', delList, imageList.value,props.type);
  } else {
    let delIndex = null;
    imageList.value.filter((item, index) => {           // 通用列表数据
      if (item.uuid === e.file.uuid) {
        delIndex = index;
      }
      return item;
    });
    imageList.value.splice(delIndex, 1);
    addList.filter((item, index) => {               // 新增列表数据
      if (item.uuid === e.file.uuid) {
        delIndex = index;
      }
      return item;
    });
    addList.splice(delIndex, 1);
    emits('imageListArray', addList, imageList.value,props.type)
  }
}

let quality = ref(100);
let compressedWidth = ref(0);
let compressedHeight = ref(0);
// 新增图片
const afterRead = async (event) => {
  // 此时可以自行将文件上传至服务器
  let lists = [].concat(event.file);
  if (uploadIf.value) {
    for (let i = 0; i < lists.length; i++) {
      const file = lists[i];
      // 获取图片信息
      uni.getImageInfo({
        src: file.url,
        success: async (result) => {
          console.log('result', JSON.stringify(result))
          compressedWidth.value = result.width;
          compressedHeight.value = result.height;
          console.log('compressedWidth', compressedWidth.value)
          console.log('compressedHeight', compressedHeight.value)
          const size = (file.size) / 1024 / 1024
          if (size > 10) {
            quality.value = 100
            compressedWidth.value = result.width / 4;
            compressedHeight.value = result.height / 4;
            console.log(1)
          }
          if (size > 5 && size <= 10) {
            quality.value = 100
            compressedWidth.value = result.width / 3.5;
            compressedHeight.value = result.height / 3.5;
            console.log(1)
          } else if (size > 2 && size <= 5) {
            quality.value = 100
            compressedWidth.value = result.width / 3;
            compressedHeight.value = result.height / 3;
            console.log(2)
          } else if (size > 1 && size <= 2) {
            quality.value = 100
            compressedWidth.value = result.width / 2;
            compressedHeight.value = result.height / 2;
            console.log(3)
          } else if (size > 0.6 && size <= 1) {
            quality.value = 100
            compressedWidth.value = result.width / 2;
            compressedHeight.value = result.height / 2;
            console.log(4)
          }
          if (size > 0.6) {
            console.log(5)
            await compressAndUpload(lists[i], lists[i].name)
          } else {
            console.log(6)
            await uploadFile(lists[i].name, lists[i].url)
          }
        }
      })
    }
  }
}

const compressAndUpload = async (file,name) => {
  try {
    console.log('compressAndUploadcompressedWidth',compressedWidth.value)
    console.log('compressAndUploadcompressedHeight',compressedHeight.value)
    // 压缩图片
    uni.compressImage({
      src: file.url, // 图片的路径
      quality: quality.value, // 图片质量，范围0-100
      compressedWidth: compressedWidth.value,
      compressedHeight: compressedHeight.value,
      success:async (res) => {
        const compressedFile = res.tempFilePath; // 压缩后的图片路径
        console.log(res,file);
        await uploadFile(name, compressedFile);
      },
      fail(err) {
        console.error('图片压缩失败', err);
      },
    });
  } catch (error) {
    console.error('压缩图片过程中发生错误', error);
  }
}

const uploadFile = async (name,url) => {
  // 使用压缩后的图片进行上传操作
  let oParams = {
    type: props.type,
    base64: '',
    originalFilename: name,
    contentType: '',
    tableName: props.tableName,
    place: props.place
  }
  console.log('oParams=',JSON.stringify(oParams))
  console.log('url=',url)

  const res1 = await proxy.http.upload(props.watermarkFlag ? api.appUploadPlaceWatermark : api.fileUpload, oParams,url, true, '', '', false);
  console.log('res1=',JSON.stringify(res1))
  const resdata = JSON.parse(res1);

  if(resdata.code === 0) {
    let oItem = {
      fileId: resdata.data.fileId,
      url: resdata.data.path,
      path: resdata.data.path,
      type: props.type,
      name: resdata.data.name,
      extname: '',
      filePath: resdata.data.filePath,
      fileType: resdata.data.fileType,
      fileSize: resdata.data.fileSize,
      uuid: generateNonceStr()
    }
    imageList.value.push(oItem);
    addList.push(oItem);
    emits('imageListArray', addList, imageList.value,props.type)
  }
}
defineExpose({
  init,
})
watchEffect(()=>{
  init();
})

</script>
<style scoped lang="scss">
.form {}
</style>
